from odoo import fields, models, api, _
from odoo.exceptions import UserError, ValidationError


class WorkflowCheckWizard(models.TransientModel):
    _name = "workflow.check.wizard"
    _description = "Approval Dialog"

    sb_workflow_item_id = fields.Many2one('sb.workflow.item', string="Approval Item",
                                          default=lambda self: self.env.context.get('sb_workflow_item_id', False))
    sb_workflow_id = fields.Many2one('sb.workflow', string="Approval Workflow",
                                     related='sb_workflow_item_id.sb_workflow_id')
    audit_level = fields.Integer(related='sb_workflow_item_id.audit_level', string="Approval Level")
    item_ids = fields.Many2many('sb.workflow.item', string="Approval Items", compute='compute_item_ids')
    sb_return_workflow_item_id = fields.Many2one('sb.workflow.item', string="Returns Approval Item")
    approval_instructions = fields.Text(string="Approval Instructions")
    is_returns = fields.Boolean(string="Returns")
    workflow_type = fields.Char()
    is_plan = fields.Boolean(string='Plan or not', default=False)

    @api.onchange('is_returns')
    @api.depends("sb_workflow_item_id")
    def compute_item_ids(self):
        for record in self:
            domain = [('sb_workflow_id', '=', record.sb_workflow_id.id), ('audit_level', '<', record.audit_level)]
            item = self.env['sb.workflow.item'].search(domain)
            record.item_ids = item.ids
            if record.is_returns:
                self.with_context(un_active=True)

    @api.model
    def default_get(self, fields):
        res = super(WorkflowCheckWizard, self).default_get(fields)
        res.update({
            'workflow_type': self.env.context.get('workflow_type', '0'),
            'is_plan': self.env.context.get('is_plan', 0),
        })
        return res

    # 审核通过
    def approval_pass(self):
        if self.sb_workflow_item_id:
            self.sb_workflow_item_id.write({
                'state': 'pass',
                'approval_time': fields.Datetime.now(),
                'user_id': self.env.user.id,
                'approval_instructions': self.approval_instructions or '通过'
            })
            # 进行中的同层级：
            tong_item_ids = self.env['sb.workflow.item'].search(
                [('sb_workflow_id', '=', self.sb_workflow_item_id.sb_workflow_id.id),
                 ('audit_level', '=', self.sb_workflow_item_id.audit_level),
                 ('state', '=', 'approval')])
            if not tong_item_ids:
                # 如有层级审核开放下一层级审核
                sb_workflow_id = self.sb_workflow_item_id.sb_workflow_id
                # 该审核所有审核流层级
                workflow_level_ids = []
                for workflow_item in sb_workflow_id.sb_workflow_item_ids:
                    workflow_level_ids.append(workflow_item.audit_level)
                # 去重排序
                qc_workflow_level_ids = list(set(workflow_level_ids))
                qc_workflow_level_ids.sort()
                # 开放一下层级
                index = qc_workflow_level_ids.index(self.sb_workflow_item_id.audit_level)
                if index + 1 < len(qc_workflow_level_ids):
                    next_audit_level = qc_workflow_level_ids[index + 1]
                    for item in sb_workflow_id.sb_workflow_item_ids:
                        if item.audit_level == next_audit_level and item.state == 'wait_forward':
                            item.state = 'approval'

    def approval_no_pass(self):
        if not self.approval_instructions:
            raise UserError(_('Please fill in the reason for the rejection'))
        if self.sb_workflow_item_id:
            self.sb_workflow_item_id.write({
                'state': 'no_pass',
                'approval_time': fields.Datetime.now(),
                'user_id': self.env.user.id,
                'approval_instructions': self.approval_instructions
            })

    def returns(self):
        # 主
        sb_workflow_id = self.sb_workflow_id
        # 当前审核
        # sb_workflow_item_id = self.sb_workflow_item_id
        # 退回节点
        sb_return_workflow_item_id = self.sb_return_workflow_item_id
        sb_return_workflow_item_id.write({'state': 'approval',
                                          'user_id': False,
                                          'approval_time': False,
                                          'approval_instructions': False})
        returns_level = sb_return_workflow_item_id.audit_level
        sb_workflow_item_ids = sb_workflow_id.sb_workflow_item_ids.filtered(
            lambda x: x.audit_level > returns_level and x.state != 'wait_forward')
        sb_workflow_item_ids.update({'state': 'wait_forward',
                                     'user_id': False,
                                     'approval_time': False,
                                     'approval_instructions': False})
